package com.fastmobile.xml;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.fastmobile.dto.Xml1Dto;
import com.fastmobile.dto.Xml2Dto;
import com.fastmobile.util.Constant;
import com.fastmobile.util.Util;

public class XmlProcess implements XmlService{
	public Xml2Dto readXml(String filepath) {
		try {
			Xml2Dto xml2Dto = new Xml2Dto();
			File file = new File(filepath);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(file);
			document.getDocumentElement().normalize();
			
			System.out.println("Root file: " + 
					document.getDocumentElement().getNodeName());
			
			NodeList nodes = document.getElementsByTagName(Constant.XML_ITEMS);
			String distance = "";
			String longtitude = "";
			String latitude = "";
			String fuel = "";
			String findFeedBack = "";
			String lockFeedBack = "";
			String unlockFeedBack = "";
			for (int i = 0; i < nodes.getLength(); i++) {
				Node node = nodes.item(i);
				if (Node.ELEMENT_NODE == node.getNodeType()) {
					Element element = (Element) node;
					distance = getValue(Constant.XML_2_KHOANG_CACH, element);
					xml2Dto.setDistance(distance);
						
					longtitude = getValue(Constant.XML_2_KINH_DO, element);
					xml2Dto.setLongtitute(longtitude);
						
					latitude = getValue(Constant.XML_2_VI_DO, element);
					xml2Dto.setLatitute(latitude);
						
					fuel = getValue(Constant.XML_2_NHIEN_LIEU, element);
					xml2Dto.setFuel(fuel);
						
					findFeedBack = getValue(Constant.XML_2_PHANHOI_TIMXE, element);
					xml2Dto.setFindFeedBack(findFeedBack);
						
					lockFeedBack = getValue(Constant.XML_2_PHANHOI_LOCK, element);
					xml2Dto.setLockFeedBack(lockFeedBack);
						
					unlockFeedBack = getValue(Constant.XML_2_PHANHOI_UNLOCK, element);
					xml2Dto.setUnlockFeedBack(unlockFeedBack);
						
					System.out.println("Khoang cach: " + xml2Dto.getDistance());
					System.out.println("Kinh do: " + xml2Dto.getLongtitute());
					System.out.println("Vi do: " + xml2Dto.getLatitute());
					System.out.println("Nhien lieu: " + xml2Dto.getFuel());
					System.out.println("Phan hoi lock: " + xml2Dto.getLockFeedBack());
					System.out.println("Phan hoi unlock: " + xml2Dto.getUnlockFeedBack());
					System.out.println("Phan hoi tim xe: " + xml2Dto.getFindFeedBack());
				}
			}
			return xml2Dto;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void modifyXml(String filepath, Xml1Dto xml1Dto) {
		try {
			File file = new File(filepath);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(file);
			document.getDocumentElement().normalize();
			updateElementValue(document, xml1Dto);
			document.getDocumentElement().normalize();
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new File(filepath));
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(source, result);
            System.out.println("XML file updated successfully");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void updateElementValue(Document doc, Xml1Dto xml1Dto) {
        NodeList items = doc.getElementsByTagName(Constant.XML_ITEM);
        Element item = null;
        for(int i = 0; i < items.getLength(); i++){
            item = (Element) items.item(i);
            item.getElementsByTagName(Constant.XML_1_TIM_XE).item(0).getFirstChild()
            	.setNodeValue(xml1Dto.isAlert());
            item.getElementsByTagName(Constant.XML_1_LOCK).item(0).getFirstChild()
            	.setNodeValue(xml1Dto.isLock());
            item.getElementsByTagName(Constant.XML_1_UNLOCK).item(0).getFirstChild()
    			.setNodeValue(xml1Dto.isUnlock());
            item.getElementsByTagName(Constant.XML_1_STATUS).item(0).getFirstChild()
				.setNodeValue(xml1Dto.isStatus());
        }
    }
	
	
	private String getValue(String tag, Element element) {
		NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
		Node node = (Node) nodes.item(0);
		return node.getNodeValue();
	}
}
